package com.edison.demo.until;

/**
 * @author edison
 */
public class LuhnUtils {

    private LuhnUtils(){
        throw new IllegalStateException("can't be instantiated");
    }

    /**
     * Generates the check digit for a bank card number using the Luhn algorithm.
     * The process of validation is as follows:
     * 1. Starting from the last digit of the card number, sum the digits at odd positions (1st, 3rd, 5th, etc.).
     * 2. Starting from the last digit, for the even-positioned digits, multiply by 2 (if the product is a two-digit number, subtract 9), then sum the results.
     * 3. Add the sum of the odd-position digits to the sum of the modified even-position digits, and the result should be divisible by 10.
     */
    public static int getLuhnSum(char[] chs) {
        int luhnSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhnSum += k;
        }
        return luhnSum;
    }
}
